import axios from "axios";
import {admin, crowd, publisher} from "@/store/pojo/Position";
import {IUser} from "@/store/pojo/IUser";
import {UserStoreModule} from "@/store/modules/User";
import router from "@/router";

const logIn = async (user: IUser) => {
    const position = user.position;
    const phone = user.phone;
    const password = user.password;

    let url = "/api/";
    if (position === crowd.toString()) {
        url += crowd.toString();
    } else if (position == admin.toString()) {
        url += admin.toString();
    } else if (position == publisher.toString()) {
        url += publisher.toString();
    }
    url += "/logIn";
    await axios.get(url, {
        params: {
            phone, password
        }
    }).then(function (response) {
        //保存信息到store

        //跳转至主页
        if (response.data != '') {
            alert("登陆成功");
            const userInfo: IUser = {
                id: response.data.id,
                email: response.data.email,
                password: response.data.password,
                phone: response.data.phone,
                username: response.data.username,
                position: user.position
            };

            UserStoreModule.setUserInfo(userInfo);

            UserStoreModule.setUserInfoToSessionStorage(userInfo);


            router.push({

                path: `/user/${position}/workspace`,
                query: {
                    userId: userInfo.id
                }
            });
        } else {
            alert("登陆失败，即将回到登陆页");
            router.push("/user/login");
        }

    })
}

export default logIn;
